#include "FileRevisionParser.h"

#include "SoftwarePackageParser.h"
#include "QStringParser.h"

#include <QXmlStreamReader>
#include <QString>

namespace Ipc2581b
{

FileRevisionParser::FileRevisionParser(
    QStringParser *&_fileRevisionIdParser
    , QStringParser *&_commentParser
    , QStringParser *&_labelParser
    , SoftwarePackageParser *&_softwarePackageParser
):    m_fileRevisionIdParser(_fileRevisionIdParser)
    , m_commentParser(_commentParser)
    , m_labelParser(_labelParser)
    , m_softwarePackageParser(_softwarePackageParser)
{

}

bool FileRevisionParser::parse(QXmlStreamReader *reader)
{
    /* Pre */

    m_result.reset(new FileRevision());

    /* Attributes */

    QStringRef data;
    if (reader->attributes().hasAttribute(QStringLiteral("fileRevisionId")))
    {
        data = reader->attributes().value(QStringLiteral("fileRevisionId"));
        if (!m_fileRevisionIdParser->parse(reader, data))
            return false;
        m_result->fileRevisionId = m_fileRevisionIdParser->result();
    }
    else
    {
        reader->raiseError(QStringLiteral("fileRevisionId: Attribute is required"));
        return false;
    }
    if (reader->attributes().hasAttribute(QStringLiteral("comment")))
    {
        data = reader->attributes().value(QStringLiteral("comment"));
        if (!m_commentParser->parse(reader, data))
            return false;
        m_result->comment = m_commentParser->result();
    }
    else
    {
        reader->raiseError(QStringLiteral("comment: Attribute is required"));
        return false;
    }
    if (reader->attributes().hasAttribute(QStringLiteral("label")))
    {
        data = reader->attributes().value(QStringLiteral("label"));
        if (!m_labelParser->parse(reader, data))
            return false;
        m_result->labelOptional = Optional<QString>(m_labelParser->result());
    }

    /* Elements */

    while (reader->readNextStartElement())
    {
        auto name = reader->name();
        if (name == QStringLiteral("SoftwarePackage"))
        {
            if (!m_softwarePackageParser->parse(reader))
                return false;
            auto result = m_softwarePackageParser->result();
            m_result->softwarePackage = result;
        }
        else
            reader->skipCurrentElement();
    }

    /* Post */

    // TODO: Check multiplicity of elements/attributes

    return true;
}

FileRevision *FileRevisionParser::result()
{
    return m_result.take();
}

}